import os
import time
import hmac
import hashlib
import base64
from urllib.parse import quote_plus
import requests


def get_gmt_date():
    """获取当前时间的 GMT 格式日期"""
    return time.strftime("%a, %d %b %Y %H:%M:%S GMT", time.gmtime())


def sign_request(access_key_secret, verb, content_md5, content_type, date, canonicalized_headers, canonicalized_resource):
    """生成签名"""
    string_to_sign = f"{verb}\n{content_md5}\n{content_type}\n{date}\n{canonicalized_headers}{canonicalized_resource}"
    h = hmac.new(access_key_secret.encode(), string_to_sign.encode(), hashlib.sha1)
    return base64.b64encode(h.digest()).decode()


def main():
    # 设置环境变量
    access_key_id = os.environ.get("")
    access_key_secret = os.environ.get("")
    endpoint = ""  # 替换为你的区域 Endpoint
    project_name = ""       # 替换为你的项目名称
    logstore_name = ""     # 替换为你的日志库名称

    # 动态生成时间戳
    from_time = int(time.time()) - 15 * 60  # 15 分钟前
    to_time = int(time.time())              # 当前时间

    # 构造 URL 参数
    query = "level:error"
    url_path = f"/logstores/{logstore_name}?type=log&topic=&from={from_time}&to={to_time}&query={quote_plus(query)}"

    # 构造请求头
    host = f"{project_name}.{endpoint}"
    date = get_gmt_date()
    canonicalized_headers = "x-log-apiversion:0.6.0\nx-log-bodyrawsize:0\nx-log-signaturemethod:hmac-sha1"
    canonicalized_resource = url_path

    # 计算签名
    signature = sign_request(
        access_key_secret,
        verb="GET",
        content_md5="",
        content_type="",
        date=date,
        canonicalized_headers=canonicalized_headers,
        canonicalized_resource=canonicalized_resource
    )
    authorization = f"LOG {access_key_id}:{signature}"

    headers = {
        "Authorization": authorization,
        "Date": date,
        "Host": host,
        "x-log-bodyrawsize": "0",
        "x-log-apiversion": "0.6.0",
        "x-log-signaturemethod": "hmac-sha1"
    }

    # 发送请求
    url = f"https://{host}{url_path}"
    response = requests.get(url, headers=headers)

    # 打印结果
    if response.status_code == 200:
        print("Response:", response.json())
    else:
        print(f"Error: {response.status_code}, {response.text}")


if __name__ == "__main__":
    main()